package com.gcb.service.impl;

import com.gcb.constant.RedisConstant;
import com.gcb.dao.CheckGroupDao;
import com.gcb.dao.SetMealDao;
import com.gcb.entity.PageResult;
import com.gcb.entity.QueryPageBean;
import com.gcb.pojo.CheckGroup;
import com.gcb.pojo.CheckItem;
import com.gcb.pojo.Setmeal;
import com.gcb.service.SetMealService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.*;

/**
 * @Author 35235
 * @Date 2021/8/6 12:58
 * @Version 1.0
 */
@DubboService(interfaceClass = SetMealService.class)
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    SetMealDao setMealDao;

    @Autowired
    CheckGroupDao checkGroupDao;

    @Autowired
    JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public List<CheckGroup> findAllCheckgroup() {
        return setMealDao.findAllCheckgroup();
    }

    @Override
    public PageResult queryQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setMealDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page);
    }

    @Override
    public boolean add(Integer[] checkGroupIds, Setmeal setmeal) {
        int count1 = setMealDao.insertSetMeal(setmeal);
        int setMealId = setmeal.getId();
        boolean result = true;
        //将图片名称保存到Redis集合中
        String fileName = setmeal.getImg();
        if (fileName != null) {
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
        }
        for (int checkGroupId : checkGroupIds) {
            HashMap<String, Integer> map = new HashMap<>();
            map.put("checkGroupId", checkGroupId);
            map.put("setMealId", setMealId);
            int count2 = setMealDao.insertSetMealCheckGroup(map);

            // 当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
            generateMobileStaticHtml();
            if (count2 == 0) {
                result = false;
                System.out.println("关系表插入出错了");
            }
        }
        return result;
    }

    @Override
    public boolean delete(Integer id) {
        int delete1 = setMealDao.deleteSetMealCheckGroup(id);
        int delete2 = setMealDao.delete(id);
        if (delete2 != 0 || delete1 != 0) {
            System.out.println("删除成功");
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setMealDao.findById(id);
        return setmeal;
    }

    @Override
    public Integer[] findCheckGroupIdsBySetMealId(Integer id) {
        Integer[] checkGroupIdsBySetMealId = setMealDao.findCheckGroupIdsBySetMealId(id);
        System.out.println("checkGroupIdsBySetMealId = " + checkGroupIdsBySetMealId);
        System.out.println(Arrays.toString(checkGroupIdsBySetMealId));
        return checkGroupIdsBySetMealId;
    }

    @Override
    public boolean update(Integer[] checkGroupIds, Setmeal setmeal) {
        int updateCount = setMealDao.updateSetMeal(setmeal);
        Map<String, Object> map = new HashMap<>();
        int deleteCount = setMealDao.deleteSetMealCheckGroup(setmeal.getId());
        int insertCount = 0;
        System.out.println(Arrays.toString(checkGroupIds));
        for (Integer checkGroupId : checkGroupIds) {
            map.put("setMealId", setmeal.getId());
            map.put("checkGroupId", checkGroupId);
            insertCount = setMealDao.insertSetMealCheckGroup(map);
        }

        return true;
    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    @Override
    public List<CheckGroup> findCheckGroupsByIds(Integer[] ids) {
        List<CheckGroup> checkGroups = new ArrayList<>();
        for (Integer id : ids) {
            CheckGroup checkGroup = setMealDao.findCheckGroupById(id);
            checkGroups.add(checkGroup);
        }
        return checkGroups;
    }

    @Override
    public List<CheckItem> findCheckItemsById(Integer id) {

        Integer[] checkItemIdsByCheckGroupId = checkGroupDao.findCheckItemIdsByCheckGroupId(id);

        List<CheckItem> checkItems = setMealDao.findCheckItemsByIds(checkItemIdsByCheckGroupId);

        for (CheckItem checkItem : checkItems) {
            System.out.println("checkItem = " + checkItem);
        }

        return checkItems;
    }

/**
 * @Author: 35235
 * @Description:生成模板页面
 * @Date: 2021/8/12 11:54
 * @param:
 * @return:
 */
    /**
     * 生成当前方法所需的静态页面
     */
    public void generateMobileStaticHtml() {
        // 在生成静态页面之前需要查询数据
        List<Setmeal> list = setMealDao.findAll();

        // 需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        // 需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    /**
     * 通用的方法，用于生成静态页面
     *
     * @param templateName
     * @param htmlPageName
     * @param map
     */
    public void generteHtml(String templateName, String htmlPageName, Map map) {
        // 获得 FreeMarker 配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();

        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成套餐列表静态页面
     *
     * @param list
     */
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList", list);
        generteHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    /**
     * 生成套餐详情静态页面（可能有多个）
     *
     * @param list
     */
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            System.out.println("setmeal = " + setmeal);
        }
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal", setMealDao.findById4Detail(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

}
